import request from "../utils/request.js";
import {splitDetail, flattenMenu, getProductPayload, matchMenuProducts} from "../utils/coffee.js";
import { dropOrder } from "./chadan.js";
import config from "../config.js";
import { retry } from "../utils/index.js";
import { getToken } from "./chadan-login.js";
import { OrderError } from "../utils/Errors.js";



export async function checkState() {
  const res = await request({
    url: config.orderBaseUrl + '/api/chaDan/status'
  });
  if(res.data.Rcode !== '000000'){
    throw new Error(`下单接口暂不可用，${JSON.stringify(res.data)}`)
  }
}

export async function getStarbucksProductMap(product) {
  const res = await request({
    url: config.orderBaseUrl + '/api/chaDan/product',
    params: { chaDanProductName: product.productName.replaceAll('·', '') }
  });

  const { data } = res;
  console.log(`下单商品(${product.productName})查询结果` +  JSON.stringify(data));
  if(data.Rcode !== '000000'){
    throw new Error(`${product.productName}查询失败，${data?.Desc}`);
  }
  const ProductDetailsString = data.Data.ProductDetails || '[]';
  try {
    const products = JSON.parse(ProductDetailsString);
    if(products.length === 0) {
      throw new Error('ProductDetails 为空');
    }
    return products.map(v => ({
      name: v.Name,
      qty: v.Qty * product.amount,
    }))
  }catch (err){
    throw new Error(`${product.productName}查询失败，${err.message}`);
  }
}

export async function getMenus(storeId) {
  console.log(`开始获取门店菜单，storeId: ${storeId}`);
  const res = await request({
    url: 'https://jk.mulinyun.com/api/menu',
    params: {
      storeId
    }
  });
  if(res.data.code === 100) {
    console.log(`获取门店菜单成功，storeId: ${storeId}`);
    return res.data.data;
  }else {
    throw new Error(`获取门店菜单失败, storeId: ${storeId}, error: ${res.data?.message}`);
  }
}

export async function getProductDetail(product, storeId) {
  console.log(`开始获取商品详情，storeId: ${storeId}，productId: ${product.id}`);
  const res = await request({
    url:  'https://jk.mulinyun.com/api/product',
    params: {
      productId: product.id,
      storeId
    }
  });
  if(res.data.code === 100) {
    console.log(`获取商品详情成功，storeId: ${storeId}，productId: ${product.id}`);
    return res.data.data
  }else {
    throw new Error(`获取商品详情失败，storeId: ${storeId} - product: ${product.name}(${product.id}), error: ${JSON.stringify(res.data)} `);
  }
}

export async function postOrder(order) {
  const { detail } = order;
  const info = splitDetail(detail);
  console.log(`detail 格式化成功：${JSON.stringify(info)}`);
  const storeId = info['门店编号'];

  let orderProducts = [];
  try {
    const productList = await Promise.all(
      order.products.map(v => retry(getStarbucksProductMap)(v))
    );
    orderProducts = order.products.map((item, index) => ({
      ...item,
      matchProducts: productList[index]
    }));
  }catch (e) {
    console.error(e);
    // 未配置商品名称映射
    throw new OrderError(`暂无下单渠道`);
  }

  let menuProducts = [];
  try {
    const menu = await retry(getMenus)(storeId);
    menuProducts = flattenMenu(menu);
  }catch (e) {
    console.error(e);
    // 获取菜单失败
    throw new OrderError(`暂无下单渠道`);
  }

  try {
    for (const item of orderProducts) {
      item.starbucksProducts = matchMenuProducts(menuProducts, item.matchProducts);
    }
  }catch (e) {
    console.error(e);
    throw new OrderError('餐厅暂无部分产品');
  }

  const allStarbucksProducts = orderProducts.flatMap(v => v.starbucksProducts);

  try {
    const result = await Promise.all(
      allStarbucksProducts.map(p => retry(getProductDetail)(p, storeId))
    );
    allStarbucksProducts.forEach((item, index) => {
      item.productDetail = result[index];
    });
  }catch (e) {
    console.error(e);
    // 获取详情失败
    throw new OrderError('暂无下单渠道');
  }

  let postProductsList = [];
  try {
    for (const product of orderProducts) {
      for (const starbucksProduct of product.starbucksProducts) {
        const itemPayload = getProductPayload(starbucksProduct.productDetail, product);
        itemPayload.qty = starbucksProduct.qty;
        itemPayload.markPrice = (itemPayload.markPrice / 100).toFixed(2);
        postProductsList.push(itemPayload);
      }
    }
  }catch (e) {
    console.error(e);
    throw new OrderError('子产品配料未查到');
  }
  const totalAmount = postProductsList.reduce((acc, v) => acc + v.qty, 0);
  const salePrice =  (order.price / totalAmount).toFixed(2);
  const payload = {
    outOrderId: order.id,
    outOrderNo: order.orderNo,
    sessionId: await getToken(),
    chanDanOrderJson: JSON.stringify(order),
    storeId,
    shopName: info['门店'],
    // storeId: '000000',
    // shopName: '测试订单，勿下单',
    shopAddress: info['门店地址'],
    shopCity: info['地区'],
    products: postProductsList.map(v => ({ ...v, salePrice })),
    totalAmount,
    totalPrice: order.price,
  }
  console.log(`获取选项成功，提交订单-${JSON.stringify(payload)}`);
  debugger
  // return
  try {
    const res = await retry(request)({
      url: config.orderBaseUrl + '/api/chaDan/order/submit',
      method: 'POST',
      data: payload,
    });
    debugger;
    if(res.data.Rcode === '000000'){
      console.log(`${order.id},${order.orderNo},下单成功, ${JSON.stringify(res.data)}`);
    }else {
      throw new Error(`${order.id}下单失败, ${JSON.stringify(res.data)}`)
    }
  }catch (e) {
    console.error(e);
    throw new OrderError('暂无下单渠道');
  }
}
